import https from 'https';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import tls from 'tls';

// 设置服务器根目录为当前文件所在目录
const rootDir = path.dirname(new URL(import.meta.url).pathname);

// 生成自签名证书
const generateSelfSignedCert = () => {
  const key = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
  const cert = crypto.createCertificate({
    key: key.privateKey,
    subject: { CN: 'localhost' },
    validityDays: 30,
  });

  return {
    key: key.privateKey.export({ type: 'pkcs1', format: 'pem' }),
    cert: cert.export({ type: 'pem', format: 'pem' }),
  };
};

const credentials = generateSelfSignedCert();

// 创建HTTPS服务器
const server = https.createServer(credentials, (req, res) => {
  // 解析请求路径
  let filePath = path.join(rootDir, req.url === '/' ? '/A.html' : req.url);

  // 检查文件是否存在
  fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
      res.writeHead(404, { 'Content-Type': 'text/html' });
      res.end('<h1>404 Not Found</h1>');
      return;
    }

    // 确定文件MIME类型
    const extname = path.extname(filePath);
    let contentType = 'text/html';

    switch (extname) {
      case '.js':
        contentType = 'text/javascript';
        break;
      case '.css':
        contentType = 'text/css';
        break;
      case '.json':
        contentType = 'application/json';
        break;
      case '.png':
        contentType = 'image/png';
        break;
      case '.jpg':
        contentType = 'image/jpg';
        break;
      case '.gif':
        contentType = 'image/gif';
        break;
    }

    // 读取并返回文件内容
    fs.readFile(filePath, (err, content) => {
      if (err) {
        res.writeHead(500);
        res.end('Internal Server Error');
        return;
      }

      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf8');
    });
  });
});

// 启动服务器
const port = 8080;
server.listen(port, () => {
  console.log(`HTTPS Server running on https://localhost:${port}`);
  console.log('Serving files from:', rootDir);
  console.log('Available files:');
  console.log('- https://localhost:8080/A.html');
  console.log('- https://localhost:8080/B.html');
});
